package com.ifonly.render;

import com.google.common.base.Strings;
import com.ifonly.config.Configuration;
import com.ifonly.logger.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-10 13:55
 * @since JDK 1.6
 */
public abstract class Render {

    protected static final String CHARSET_PROP = "; charset=";

    protected Configuration config = Configuration.getInstance();
    protected Logger logger;

    protected HttpServletRequest request;
    protected HttpServletResponse response;

    protected String viewDir;
    protected String view;
    protected String extension;

    public Render() {
    }

    public Render(String view, String extension) {
        this.view = view;
        this.extension = extension;
    }

    public Render init(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.logger = Logger.getLogger(Render.class);
        return this;
    }

    public Render init(HttpServletRequest request, HttpServletResponse response, String view) {
        this.request = request;
        this.response = response;
        this.view = view;
        this.logger = Logger.getLogger(Render.class);
        return this;
    }

    public Render setViewDir(String viewDir) {
        this.viewDir = viewDir;
        return this;
    }

    private String appendToPath(String path, String target) {
        if (path.endsWith("/") && target.startsWith("/")) {
            path = path + target.substring(1);
        } else {
            if (path.endsWith("/")) {
                path = path + target;
            } else if (target.startsWith("/")) {
                path = path + target;
            } else {
                path = path + "/" + target;
            }
        }
        return path;
    }

    protected String getView() {
        String path = Configuration.getInstance().getViewPath();
        /*if (view.startsWith("/")) {
            path = path + view;
        } else {
            if (Strings.isNullOrEmpty(viewDir)) {
                path = path + "/" + viewDir + "/" + view;
            } else {
                path = path + "/" + view;
            }
        }
        path = path.replaceAll("/{2,}", "/");*/

        if (view.startsWith("/")) {
            if (path.endsWith("/")) {
                path = path + view.substring(1);
            } else {
                path = path + view;
            }
        } else {
            if (!Strings.isNullOrEmpty(viewDir)) {
                path = appendToPath(path, viewDir);
            }

            path = appendToPath(path, view);
        }


        if (!Strings.isNullOrEmpty(extension) && !path.endsWith(extension)) {
            path = path + extension;
        }
        return path;
    }


    public abstract void render();

}
